package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.info.AppVersionInfo;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * HarmonyOS应用包解析工具（增强版）
 * 支持解析module.json和pack.info并提取应用版本信息
 */
public final class HarmonyAppVersionParser {
    // 配置文件路径常量
    private static final String MODULE_JSON = "module.json";
    private static final String PACK_INFO = "pack.info";
    private static final String MEDIA_DIR = "resources/base/media/";
    private static final Pattern IMAGE_PATTERN =
            Pattern.compile(".*\\.(png|jpg|jpeg|webp|bmp)$", Pattern.CASE_INSENSITIVE);

    // API版本映射表（根据官方文档维护）
    private static final Map<Integer, String> API_VERSION_MAP = new HashMap<>();
    static {
        API_VERSION_MAP.put(8, "3.0");
        API_VERSION_MAP.put(9, "3.1");
        API_VERSION_MAP.put(10, "3.1");
        API_VERSION_MAP.put(11, "3.1");
        API_VERSION_MAP.put(12, "3.1");
        API_VERSION_MAP.put(13, "3.2");
        API_VERSION_MAP.put(14, "3.2");
        API_VERSION_MAP.put(15, "4.0");
        // 后续版本继续补充...
    }

    /**
     * 解析HAP文件获取版本信息
     */
    public static AppVersionInfo parse(InputStream hapStream) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(hapStream)) {
            AppVersionInfo versionInfo = new AppVersionInfo();
            boolean hasModuleJson = false;

            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String entryName = entry.getName();

                // 1. 解析核心配置文件
                if (MODULE_JSON.equals(entryName)) {
                    parseModuleJson(IOUtils.toString(zis, StandardCharsets.UTF_8), versionInfo);
                    hasModuleJson = true;
                }
                // 2. 解析备用配置
                else if (PACK_INFO.equals(entryName)) {
                    parsePackInfo(IOUtils.toString(zis, StandardCharsets.UTF_8), versionInfo);
                }
                // 3. 提取应用图标（用于版本展示）
                else if (entryName.startsWith(MEDIA_DIR) && IMAGE_PATTERN.matcher(entryName).matches()) {
                    if (versionInfo.getIconBytes() == null) {
                        versionInfo.setIconBytes(IOUtils.toByteArray(zis));
                        versionInfo.setIconPath(entryName);
                    }
                }
            }

            if (!hasModuleJson) {
                throw new IllegalArgumentException("Invalid HAP: Missing module.json");
            }

            // 格式化API版本
            if (versionInfo.getMinApiVersion() != null) {
               // versionInfo.setFormattedMinApiVersion(formatApiVersion(versionInfo.getMinApiVersion()));
             versionInfo.setMinApiVersion(versionInfo.getMinApiVersion());
            }
            if (versionInfo.getTargetApiVersion() != null) {
               // versionInfo.setFormattedTargetApiVersion(formatApiVersion(versionInfo.getTargetApiVersion()));
             versionInfo.setFormattedMinApiVersion(String.valueOf(versionInfo.getTargetApiVersion()));
           }

            return versionInfo;
        }
    }

    // 解析module.json主配置
    private static void parseModuleJson(String json, AppVersionInfo info) {
        JSONObject root = JSON.parseObject(json);
        JSONObject app = root.getJSONObject("app");
        JSONObject module = root.getJSONObject("module");

        // 基础信息
        info.setPackageName(app.getString("bundleName"));
        info.setVersionName(app.getString("versionName"));
        info.setVersionCode(app.getString("versionCode"));
        info.setVendor(app.getString("vendor"));
        info.setAppName(app.getString("label")); // 需要解析$string资源

        // 版本要求
        info.setMinApiVersion(app.getInteger("minAPIVersion"));
        info.setTargetApiVersion(app.getInteger("targetAPIVersion"));
        info.setCompileSdkVersion(app.getString("compileSdkVersion"));

        // 模块信息
        info.setModuleName(module.getString("name"));
        info.setMainAbility(module.getString("mainElement"));

        // 权限信息
        if (module.containsKey("requestPermissions")) {
            info.setPermissions(module.getJSONArray("requestPermissions"));
        }
    }

    // 解析pack.info备用配置
    private static void parsePackInfo(String json, AppVersionInfo info) {
        JSONObject root = JSON.parseObject(json);
        JSONObject summary = root.getJSONObject("summary");
        JSONObject app = summary.getJSONObject("app");

        // 版本信息补充
        if (info.getVersionName() == null) {
            info.setVersionName(app.getJSONObject("version").getString("name"));
        }
        if (info.getVersionCode() == null) {
            info.setVersionCode(app.getJSONObject("version").getString("code"));
        }

        // 模块信息补充
        if (!summary.getJSONArray("modules").isEmpty()) {
            JSONObject module = summary.getJSONArray("modules").getJSONObject(0);
            if (info.getMainAbility() == null) {
                info.setMainAbility(module.getString("mainAbility"));
            }

            // API版本兼容性信息
            if (module.containsKey("apiVersion")) {
                JSONObject apiVer = module.getJSONObject("apiVersion");
                if (info.getMinApiVersion() == null) {
                    info.setMinApiVersion(apiVer.getInteger("compatible"));
                }
                if (info.getTargetApiVersion() == null) {
                    info.setTargetApiVersion(apiVer.getInteger("target"));
                }
            }
        }
    }

    /**
     * 转换API版本为可读格式（如14 → "HarmonyOS 3.2"）
     */
    private static String formatApiVersion(int versionCode) {
        String version = API_VERSION_MAP.getOrDefault(versionCode, "未知");
        return "HarmonyOS " + version;
    }
}